package com.pro01.apirednote.mapper;

import com.pro01.apirednote.dto.UserSummaryDTO;
import com.pro01.apirednote.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {

    @Insert("INSERT INTO users (username, password, role, created_at) VALUES (#{username}, #{password}, 'USER', NOW())")
    int insertUser(User user);

    @Select("SELECT * FROM users WHERE username = #{username}")
    User selectByUsername(String username);

    @Select("SELECT COUNT(*) FROM users WHERE username = #{username}")
    int countByUsername(String username);

    // 获取当前用户信息
    @Select("SELECT * FROM users WHERE id = #{id}")
    User selectById(Long id);

    @Select("SELECT COUNT(*) FROM contents WHERE user_id = #{userId} AND is_deleted = FALSE")
    Integer countContentsByUser(Long userId);

    @Select("SELECT COUNT(*) FROM comments WHERE user_id = #{userId}")
    Integer countCommentsByUser(Long userId);

    @Select("SELECT COALESCE(SUM(view_count), 0) FROM contents WHERE user_id = #{userId} AND is_deleted = FALSE")
    Integer countTotalViewsByUserId(Long userId);

    @Select("""
    SELECT COUNT(*) FROM comments 
    WHERE content_id IN (SELECT id FROM contents WHERE user_id = #{userId} AND is_deleted = FALSE)
""")
    Integer countReceivedComments(Long userId);

    @Select("""
    SELECT SUM(like_count) FROM contents WHERE user_id = #{userId} AND is_deleted = FALSE
""")
    Integer sumReceivedLikes(Long userId);

    // 查询用户列表
    @Select("""
    SELECT id, username, email, role, created_at
    FROM users
    ORDER BY created_at DESC
    LIMIT #{pageSize} OFFSET #{offset}
""")
    List<UserSummaryDTO> findAllUsers(@Param("offset") int offset, @Param("pageSize") int pageSize);

    // 管理员查看所有用户信息
    @Select("SELECT * FROM users ORDER BY created_at DESC LIMIT #{limit} OFFSET #{offset}")
    List<User> selectAllUsers(@Param("limit") int limit, @Param("offset") int offset);

    @Select("SELECT COUNT(*) FROM users")
    int countAllUsers();

    // 管理员修改用户权限
    @Update("UPDATE users SET role = #{role} WHERE id = #{id}")
    int updateUserRole(@Param("id") Long id, @Param("role") String role);
}

